package smart.wallet;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import smart.wallet.db.DBAdapter;
import smart.wallet.db.DBHelper;
import smart.wallet.model.CategoryModel;
import smart.wallet.utils.ColorPickerDialog;
import smart.wallet.utils.ColorPickerDialog.OnColorChangedListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Register extends Activity implements View.OnClickListener,
		View.OnLongClickListener, OnColorChangedListener,
		OnItemSelectedListener {
	Cursor categories;
	Cursor accounts;
	long account_id;
	boolean category_advice;
	boolean color_advice;
	DBAdapter db;
	CategoryModel selected_category_model;
	CategoryModel category_model;
	static final int add_category_id = 0;
	Dialog dialog;
	Button category_color_button;
	EditText category_name;
	Spinner category_spinner;
	ImageButton add_category;
	private final int EDIT_ACTIVE_DIALOG = 1;
	private final int CREATE_ACTIVE_DIALOG = 2;
	private int active_dialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		active_dialog = 0;
		category_advice = false;
		color_advice = false;
		account_id = Home.CURRENT_ACCOUNT_ID;
		
	}
	
	private void fetchStaticCategories(){
		categories = db.fetchAllValidAccountCategories(account_id);
		
		if (categories.getCount() == 0) {
			db.createAccountCategory(account_id, "Gasolina", R.drawable.gas,
					Color.DKGRAY, 2);
			db.createAccountCategory(account_id, "Salario",
					R.drawable.paycheck, Color.GREEN, 1);
			db.createAccountCategory(account_id, "Namoro", R.drawable.dating,
					Color.RED, 2);
			db.createAccountCategory(account_id, "Super", R.drawable.market,
					Color.LTGRAY, 2);
			db.createAccountCategory(account_id, "Cartao",
					R.drawable.creditcard, Color.BLUE, 2);
			db.createAccountCategory(account_id, "Festa", R.drawable.party,
					Color.MAGENTA, 2);
			db.createAccountCategory(account_id, "Roupas", R.drawable.clothes,
					Color.YELLOW, 2);
			db.createAccountCategory(account_id, "Telefone", R.drawable.tel,
					Color.CYAN, 2);
			categories = db.fetchAllAccountCategories(account_id);
		}
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		setContentView(R.layout.register);
		
		Button add_button = (Button) findViewById(R.id.add_register);
		add_button.setOnClickListener(this);

		db = new DBAdapter(this);

		db.open();
		
		fetchStaticCategories();
		
		LinearLayout category_list = (LinearLayout) findViewById(R.id.linearLayout2);
		int i = 1;
		if (categories.getCount() > 0) {
			do {

				RelativeLayout category_item = (RelativeLayout) View.inflate(
						this, R.layout.category_item, null);
				category_item.setId(i);

				selected_category_model = new CategoryModel(
						categories.getLong(categories
								.getColumnIndexOrThrow(DBHelper.CATEGORY_ID)),
						categories.getLong(categories
								.getColumnIndexOrThrow(DBHelper.CATEGORY_ACCOUNT_ID)),
						categories.getString(categories
								.getColumnIndexOrThrow(DBHelper.CATEGORY_NAME)),
						categories.getLong(categories
								.getColumnIndexOrThrow(DBHelper.CATEGORY_IMAGE)),
						categories.getLong(categories
								.getColumnIndexOrThrow(DBHelper.CATEGORY_COLOR)),
						categories.getLong(categories
								.getColumnIndexOrThrow(DBHelper.CATEGORY_TYPE)));
				category_item.setTag(selected_category_model);

				Resources res = getResources();
				if (categories.getLong(categories
						.getColumnIndexOrThrow(DBHelper.CATEGORY_TYPE)) == 1) { // credit
					category_item.setBackgroundDrawable(res
							.getDrawable(R.drawable.category_credit));
				} else {
					category_item.setBackgroundDrawable(res
							.getDrawable(R.drawable.category_debit));
				}

				ImageView category_image = (ImageView) category_item
						.findViewById(R.id.image_icon);
				category_image
						.setImageResource((int) categories.getLong(categories
								.getColumnIndexOrThrow(DBHelper.CATEGORY_IMAGE)));
				category_image.setId(i);

				TextView text_image = (TextView) category_item
						.findViewById(R.id.image_title);
				text_image.setText(categories.getString(categories
						.getColumnIndexOrThrow(DBHelper.CATEGORY_NAME)));
				text_image.setId(i);

				category_list.addView(category_item);
				category_item.setOnClickListener(this);
				category_item.setOnLongClickListener(this);
				i++;
			} while (categories.moveToNext());

			add_category = new ImageButton(this);

			add_category.setBackgroundResource(android.R.color.transparent);
			add_category.setImageResource(R.drawable.add_selector);
			add_category.setOnClickListener(this);
			add_category.setScaleType(ScaleType.FIT_CENTER);
			add_category.setId(0);
			category_list.addView(add_category);

		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (db != null) {
			db.close();
		}
		if (categories != null) {
			categories.close();
		}
	}

	public void onClick(View view) {
		EditText value = (EditText) findViewById(R.id.register_value);
		String current_date = new SimpleDateFormat("dd/MM/yyyy").format(
				new Date()).toString();

		switch (view.getId()) {
		case R.id.add_register:

			if (validateFields()) {
				db.createRegister(account_id,
						Float.valueOf(value.getText().toString()),
						selected_category_model.getId(), "Teste", current_date);
				// clean values
				unselectCategories();
				value.setText("");

				Toast toast = Toast.makeText(this, R.string.register_added,
						Toast.LENGTH_LONG);
				toast.show();
			}
			break;
		case add_category_id:
			add_category = (ImageButton) findViewById(add_category_id);
			add_category.setSelected(true);
			Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				public void run() {
					add_category.setSelected(false);
				}
			}, 250);
			
			category_model = new CategoryModel(0, account_id, "", R.drawable.money , Color.WHITE, 1);
			
			if (!color_advice){
				Toast toast = Toast.makeText(this, R.string.category_color_advice,
						Toast.LENGTH_LONG);
				toast.show();
				color_advice = true;
			}
			createCategoryDialog();
			
			break;
		case R.id.category_color_button:

			dialog.dismiss();
			ColorPickerDialog dialog = new ColorPickerDialog(this, this,
					(int) category_model.getColor());
			dialog.show();

			break;
		default:
			if (!category_advice) {
				Toast toast = Toast.makeText(this,
						R.string.edit_delete_category_toast, Toast.LENGTH_LONG);
				toast.show();
				category_advice = true;
			}

			unselectCategories();

			view.setSelected(true);
			
			// Hidden soft keynoard
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
			

			selected_category_model = (CategoryModel) view.getTag();

			break;
		}
	}

	private void unselectCategories() {
		categories.moveToFirst();
		do {
			RelativeLayout category_item = (RelativeLayout) findViewById((int) categories
					.getLong(categories
							.getColumnIndexOrThrow(DBHelper.CATEGORY_ID)));
			category_item.setSelected(false);
		} while (categories.moveToNext());
	}

	private void createEditCategoryDialog() {
		
		active_dialog = EDIT_ACTIVE_DIALOG;
		
		
		AlertDialog.Builder builder;

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.category_dialog, null);

		category_spinner = (Spinner) layout
				.findViewById(R.id.category_type_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.category_type,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		category_spinner.setAdapter(adapter);

		category_spinner
				.setSelection((int) category_model.getType() - 1);

		category_name = (EditText) layout
				.findViewById(R.id.dialog_category_name);
		category_name.setText(category_model.getName());

		category_color_button = (Button) layout
				.findViewById(R.id.category_color_button);
		category_color_button.setBackgroundColor((int) category_model
				.getColor());
		
		category_color_button.setOnClickListener(this);
		
		builder = new AlertDialog.Builder(this);

		builder.setView(layout);

		builder.setPositiveButton(R.string.edit,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						category_model.setName(category_name.getText()
								.toString());
						category_model.setType(category_spinner
								.getSelectedItemPosition() + 1);

						db.updateAccountCategory(category_model.getId(),
								category_model.getAccount_id(),
								category_model.getName(),
								category_model.getImage(),
								category_model.getColor(),
								category_model.getType());
						
						Toast toast = Toast.makeText(Register.this, R.string.category_updated,
								Toast.LENGTH_LONG);
						toast.show();
						
						Register.this.dialog.dismiss();
						
						if (Register.this.accounts != null){
							accounts.close();
						}
						if (Register.this.categories != null){
							categories.close();
						}
						if (Register.this.db != null){
							db.close();
						}
						
						Register.this.onResume();
					}
				});

		builder.setNegativeButton(R.string.delete,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						db.logicDeleteAccountCategory(category_model.getId(), category_model.getAccount_id());
						
						Toast toast = Toast.makeText(Register.this, R.string.category_deleted,
								Toast.LENGTH_LONG);
						toast.show();
						
						Register.this.dialog.dismiss();
						
						if (Register.this.accounts != null){
							accounts.close();
						}
						if (Register.this.categories != null){
							categories.close();
						}
						if (Register.this.db != null){
							db.close();
						}
						
						Register.this.onResume();
						
						
					}
				});

		builder.setCancelable(true);

		dialog = builder.create();

		dialog.show();
	}
	
	private void createCategoryDialog() {
		
		active_dialog = CREATE_ACTIVE_DIALOG;
		
		AlertDialog.Builder builder;

		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.category_dialog, null);

		category_spinner = (Spinner) layout
				.findViewById(R.id.category_type_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.category_type,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		category_spinner.setAdapter(adapter);

		category_name = (EditText) layout
				.findViewById(R.id.dialog_category_name);
		
		category_color_button = (Button) layout
				.findViewById(R.id.category_color_button);
		category_color_button.setOnClickListener(this);
		category_color_button.setBackgroundColor((int)category_model.getColor());
		
		builder = new AlertDialog.Builder(this);

		builder.setView(layout);

		builder.setPositiveButton(R.string.create_category,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						
						category_model.setName(category_name.getText()
								.toString());
						category_model.setType(category_spinner
								.getSelectedItemPosition() + 1);
							
						db.createAccountCategory(
								category_model.getAccount_id(),
								category_model.getName(),
								category_model.getImage(),
								category_model.getColor(),
								category_model.getType());
						
						Toast toast = Toast.makeText(Register.this, R.string.category_created,
								Toast.LENGTH_LONG);
						toast.show();
						
						Register.this.dialog.dismiss();
						
						if (Register.this.accounts != null){
							accounts.close();
						}
						if (Register.this.categories != null){
							categories.close();
						}
						if (Register.this.db != null){
							db.close();
						}
						
						Register.this.onResume();
					}
				});

		builder.setCancelable(true);

		dialog = builder.create();

		dialog.show();
	}
	
	public void colorChanged(int color) {
		category_model.setColor(color);
		dialog.dismiss();
		
		if (active_dialog == CREATE_ACTIVE_DIALOG){
			createCategoryDialog();
		} else {
			createEditCategoryDialog();
		}	
	}

	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {

		category_model.setType(id);
	}

	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
	}

	private boolean validateFields() {

		EditText register_value = (EditText) findViewById(R.id.register_value);

		if (register_value.getText().toString().contentEquals("")) {
			Toast toast = Toast.makeText(this, R.string.empty_register_value,
					Toast.LENGTH_LONG);
			toast.show();
			return false;
		}
		categories.moveToFirst();
		boolean is_category_selected = false;
		do {
			RelativeLayout category_item = (RelativeLayout) findViewById((int) categories
					.getLong(categories
							.getColumnIndexOrThrow(DBHelper.CATEGORY_ID)));
			if (category_item.isSelected()) {
				is_category_selected = true;
			}
		} while (categories.moveToNext());
		if (!is_category_selected) {
			Toast toast = Toast.makeText(this, R.string.category_unselected,
					Toast.LENGTH_LONG);
			toast.show();
			return false;
		}

		return true;
	}

	public boolean onLongClick(View selected_category) {

		final Animation shake = AnimationUtils
				.loadAnimation(this, R.anim.shake);
		selected_category.startAnimation(shake);

		category_model = (CategoryModel) selected_category.getTag();
		
		if (!color_advice){
			Toast toast = Toast.makeText(this, R.string.category_color_advice,
					Toast.LENGTH_LONG);
			toast.show();
			color_advice = true;
		}
		createEditCategoryDialog();

		return false;
	}
}
